package db

import (
	"fmt"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
	"log"
	"os"
	"time"
	"video_demo/config"
)

// mysqlDB 数据库连接
var MysqlDB *gorm.DB

// Init 初始化数据库连接
func init() {
	cfg := config.SysConfig
	//dsn := "root:ldxyes2580.@tcp(120.46.69.238:3306)/derui_DB?charset=utf8mb4&parseTime=True&loc=Local"
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
		cfg.DB.User, cfg.DB.Password, cfg.DB.Host, cfg.DB.Port, cfg.DB.Name)

	logLevel := getLogLevel(cfg.Logger.LogLevel)
	slowThreshold := time.Duration(cfg.Logger.SlowThreshold) * time.Second

	newLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold:             slowThreshold,                     // Slow SQL threshold
			LogLevel:                  logLevel,                          // Log level
			IgnoreRecordNotFoundError: cfg.Logger.IgnoreNotFoundError,    // Ignore ErrRecordNotFound error for logger
			ParameterizedQueries:      cfg.Logger.UseParametrizedQueries, // Don't include params in the SQL log
			Colorful:                  cfg.Logger.Colorful,               // Disable color
		},
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger,
	})
	if err != nil {
		panic("数据库连接失败")
	}
	MysqlDB = db
}

// GetDB 返回数据库连接
func GetDB() *gorm.DB {
	return MysqlDB
}

// 根据配置文件中的日志级别返回对应的 LogLevel
func getLogLevel(logLevel string) logger.LogLevel {
	switch logLevel {
	case "info":
		return logger.Info
	case "warn":
		return logger.Warn
	case "error":
		return logger.Error
	default:
		return logger.Info // 设置默认级别
	}
}

func DBError(err error) {
	panic(err.Error())
}
